<!-- 支付页面 -->
<template>
  <view class="body">
    <view class="pay_box">
      <view class="header">
        <view class="price">￥{{ countPay() }}</view>
        <view class="tips">请您扫码付款</view>
        <view class="img">
          <image class="icon" src="../../assets/images/pages2/pay/icon1.png"></image>
          <image class="icon" src="../../assets/images/pages2/pay/icon2.png"></image>
          <image class="icon" src="../../assets/images/pages2/pay/icon3.png"></image>
        </view>
      </view>
      <!-- 二维码 -->
      <view class="code_box">
        <view v-if="codeUrl">
          <!-- <qrCode :text="codeUrl" :qrWidth="400"></qrCode> -->
          <qrCode :text="codeUrl" :qrWidth="400" @getImgUrl="handleGetImgUrl"></qrCode>
          <view class="update_tips">15分钟内有效，点击<span @click="update" class="update">刷新</span></view>
          <view class="btn" @click="saveImage">保存到相册</view>
        </view>
        <view v-else class="tips">二维码获取失败</view>
      </view>
    </view>
  </view>
</template>
    
<script lang="ts" setup>
import Taro, { useReady, useRouter } from '@tarojs/taro';
import { onMounted, ref, nextTick, reactive } from "vue";
import qrCode from '@/components/qrcode2/index.vue'
import useOrderStore from "@/store/order";
import useUserStore from "@/store/user";
import { getupdateRemarks } from "@/@api/review";
import { NewPayParam, getPaySrc, payResult } from "@/@api/order";
import { getReckLogBatch } from "@/@api/waybill";
import { payArr } from '@/pages2/waybillPage/pay.js';



useReady(() => {
  Taro.setNavigationBarTitle({
    title: '支付收银台'
  })
  Taro.setNavigationBarColor({
    frontColor: '#ffffff',
    backgroundColor: '#0966FF',
  });
  getCodeBefore(); // 二维码前先调这个
})





onMounted(() => {
  Taro.authorize({
    scope: 'scope.writePhotosAlbum',
    success() {
      console.log('获取权限成功')

    },
    fail() {
      console.log('获取权限失败')
    }
  })
})

const orderStore = useOrderStore()
const orderList = ref<any>();
orderList.value = orderStore.orderInfo
// orderList.value = payArr[0]




const userStore = useUserStore()


// const codeUrl = ref('https://ibsbjstar.ccb.com.cn/CCBIS/QR?QRCODE=CCB9980009210166651363185') // 二维码url
const codeUrl = ref('') // 二维码url
const timer = ref() // 定时器
const isfail = ref(false) // 刷新二维码


// 待支付费用
// orderList.value.costList.forEach((t) => {
//   let difference = t.money - t.paid;
//   allPay.value += difference;
// });
const allPay = ref(0); // 待付款
function countPay() {
  console.log(orderList.value, '待支付数据')
  let needPay = 0;
  orderList.value.costList.forEach((item) => {
    needPay = needPay + (item.actualMoney - item.paidMoney)
  });
  console.log(needPay, '代付款金额')
  allPay.value = needPay;
  return needPay
}

// 二维码之前的参数
const beforeParams = {
  "billNoArr": [orderList.value.billNo],
  "manageFee": []
}

// 支付二维码参数
const params = {
  "bill": {
    "billNos": [orderList.value.billNo],
    "money": countPay(),
    "actualMoney": countPay(),
    "serviceCharge": 0,
    "btssId": 1,
    "manage_fee": []
  },
  "device_info": "pp01",
  "body": "支付运单3",
  "attach": "000003069",
  // "total_fee": countPay() * 100,
  "total_fee": 1, // 1019 
  "branchno": "00002",
  "paytype": "04",
  "eop": "SYSADMIN",
  "type": "01",
  "v3": "",
  "isdebug": "True",
  "debug": true
}

async function getCodeBefore() {
  console.log(beforeParams, '二维码之前参数')
  const { data } = await getReckLogBatch(beforeParams);
  if (data.code == 200) {
    console.log(data, 'getCodeBefore返回')
    reqGetPaySrc(params);
  } else {
    codeUrl.value = '';
  }
}


// const params = {
// 	"bill": {
// 		"billNos": ["111108254"],
// 		"money": 52,
// 		"actualMoney": 52,
// 		"serviceCharge": 0,
// 		"btssId": 1
// 	},
// 	"device_info": "pp01",
// 	"body": "支付运单3",
// 	"attach": "000003069",
// 	"total_fee": 1,
// 	"branchno": "00002",
// 	"paytype": "04",
// 	"eop": "SYSADMIN",
// 	"type": "01",
// 	"v3": "",
// 	"isdebug": "True",
// 	"debug": true
// }



console.log(JSON.parse(JSON.stringify(orderStore)), '进页面的orderStore是什么');
console.log(orderList.value.billNo, 'bill-billNos')
console.log(allPay.value, 'allPay')

const imgUrl = reactive({ url: '' }); // 二维码图片url

// 获取图片url
function handleGetImgUrl(img) {
  console.log(img, '获取子传父的url')
  nextTick(() => {
    imgUrl.url = img
  });
}

// 保存相册 
function saveImage() {
  console.log(imgUrl.url, '保存到相册')
  Taro.saveImageToPhotosAlbum({
    filePath: imgUrl.url,
    success() {
      Taro.showToast({
        title: '保存成功',
        icon: 'success',
        duration: 2000
      });
    },
    fail() {
      Taro.showToast({
        title: '保存失败',
        icon: 'none',
        duration: 2000
      });
    }
  });
}

// 刷新二维码
function update() {
  codeUrl.value = "";
  reqGetPaySrc(params);
}

// 获取二维码
async function reqGetPaySrc(params: NewPayParam) {
  const { data } = await getPaySrc(params);
  if (data.code == 200) {
    let orderId = JSON.parse(data.data).ORDERID
    codeUrl.value = JSON.parse(data.data).QRCODESTRING;
    payReturn(orderId)
  } else {
    // 支付成功跳详情
  }
}

// 支付回调
async function payReturn(e) {
  clearTimeout(timer.value);
  const res = await payResult({ orderid: e })
  if (res.data.code == 200) {
    let data = JSON.parse(res.data.data.data)[0];
    if (data.STATUSCODE && data.STATUSCODE == "1") {
      clearTimeout(timer.value);
      getReview(); // 支付成功调用审核订单接口
    } else {
      timer.value = setTimeout(() => {
        console.log('未支付成功');
        // payReturn(e)
        Taro.navigateTo({
          url: '/pages2/waybillPage/payFinish'
        });
      }, 5000)
    }
  }
}

// 调用审核接口审核订单
async function getReview() {
  const { data } = await getupdateRemarks({
    ssoId: orderList.ssoId,
    isExamine: 2,
  });
  if (data.code == 200) {
    console.log('审核成功')
    // 跳转审核详情页
    Taro.navigateTo({
      url: `/pages2/pay/info?billFlag=review`
    });
  }
}







</script>
<style lang="scss">
* {
  box-sizing: border-box;
}

.body {
  box-sizing: border-box;
  width: 100vw;
  height: 100%;
  position: relative;
  background-color: #0966FF;
  padding-bottom: 12rpx;
}

.pay_box {
  width: 702rpx;
  height: 1060rpx;
  background: url('../../assets/images/pages2/pay/pay_box.png');
  background-size: 100% 100%;
  margin: 0 auto;
  text-align: center;
  padding-top: 32rpx;

  .price {
    font-size: 76rpx;
    color: #252525;
  }

  .tips {
    font-size: 32rpx;
    color: #666;
  }

  .img {
    .icon {
      width: 160rpx;
      height: 80rpx;
    }
  }

  .update_tips {
    font-size: 22rpx;
    color: #000;
    margin: 16rpx auto;

    .update {
      color: #0966FF;
      text-align: center;
      display: inline-block;
    }
  }

  .btn {
    width: 480rpx;
    height: 88rpx;
    line-height: 88rpx;
    border-radius: 200rpx;
    opacity: 1;
    border: 1rpx solid #0966FF;
    color: #0966FF;
    font-weight: bold;
    text-align: center;
    margin: 0 auto;
  }
}
</style>